package itsm.isperp.module.controller.slm;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.db.DbEntityFieldControl;
import itsm.isperp.module.entity.slm.SlmServiceTarget;
import itsm.isperp.module.service.app.AppCalendarConfigService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.slm.SlmServiceAgreementService;
import itsm.isperp.module.service.slm.SlmServiceTargetService;
import itsm.isperp.workflow.service.BpmProcessDefinitaionService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("slm/serviceTarget")
public class SlmServiceTargetController extends
		BaseController<SlmServiceTarget> {

	/**
	 * 
	 */
	@Autowired
	protected SlmServiceTargetService slmServiceTargetService;

	@Autowired
	protected SlmServiceAgreementService slmServiceAgreementService;

	@Autowired
	protected AppCalendarConfigService appCalendarConfigService;

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected ProjProjectService projectService;

	@Override
	public SlmServiceTargetService getService() {
		return slmServiceTargetService;
	}

	@Override
	public String getPageTitle() {
		return "服务目标";
	}

	@Override
	@RequestMapping("listByAgreement")
	@ResponseBody
	public PageResponse<SlmServiceTarget> list(JqGridRequest request,
			HttpServletRequest req) {

		String agreementId = req.getParameter("agreementId");
		if (StringUtils.isEmpty(agreementId)) {
			return null;
		}

		request.isPageable(false).addFilterRule("agreement_id",
				JqGridFilterRuleOp.eq, agreementId);
		return this.getService().findAll(request).toPage();

	}

	/**
	 * 服务级别编辑界面
	 * 
	 * @return 服务级别编辑界面视图
	 */
	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) {

		String agreementId = req.getParameter("agreementId");

		DbEntityFieldControl dbEntityFieldControl = null;

		SlmServiceTarget sst = null;
		String targetHours = null;
		String targetMinutes = null;

		if (StringUtils.isEmpty(id)) {
			sst = new SlmServiceTarget();
			sst.setAgreementId(agreementId);
			targetHours = "0";
			targetMinutes = "0";
		} else {
			sst = this.getService().findOne(id);
			String[] targetArr = sst.getTarget().split(":");
			targetHours = targetArr[0];
			targetMinutes = targetArr[1];
		}

		ModelAndView mv = new ModelAndView(this.getModulePath() + "/edit");
		mv.addObject("targetHours", targetHours);
		mv.addObject("targetMinutes", targetMinutes);

		mv.addObject("model", sst);
		// 状态
		// mv.addObject("slmStatus", appDictService.findByType("SLM_STATUS"));
		// 目标定义初始化（根据其关联的服务协议的应用对象（比如事件、问题），抓出其相关的状态的定义（新建、已分派、处理中、已关闭等），）

		// mv.addObject("startTaskStatus",
		// appDictService.findByType("SLM_STATUS"));
		// mv.addObject("endTaskStatus",
		// appDictService.findByType("SLM_STATUS"));

		BpmProcessDefinitaionService bs = ContextHolder
				.getSpringBean("bpmProcessDefinitaionService");
		ProcessDefinitionEntity pde = bs
				.getProcessDefinitionEntityByKey("incidentProcess");
		List<AppDict> nodeList = new ArrayList<AppDict>();
		List<AppDict> isAutoUpgradeItem = new ArrayList<AppDict>();
		List<ActivityImpl> actList = pde.getActivities();
		for (ActivityImpl ai : actList) {
			Map<String, Object> mp = ai.getProperties();
			if (mp.get("type").equals("userTask")) {
				/*
				 * Map<String,String> m1=new HashMap<String,String>();
				 * m1.put(ai.getId(),(String)mp.get("name") ); nodeList.add(m1);
				 */
				AppDict td = new AppDict();
				td.setId(ai.getId());
				td.setName((String) mp.get("name"));
				nodeList.add(td);
			}
		}
		AppDict td2 = new AppDict();
		td2.setId("1");
		td2.setName("是");
		AppDict td3 = new AppDict();
		td3.setId("0");
		td3.setName("否");
		isAutoUpgradeItem.add(td2);
		isAutoUpgradeItem.add(td3);
		mv.addObject("nodeList", nodeList);
		mv.addObject("isAutoUpgradeItem", isAutoUpgradeItem);
		if (StringUtils.isNotEmpty(sst.getAgreementId())) {
			dbEntityFieldControl = slmServiceAgreementService
					.findSlmMonitorFieldControl(sst.getAgreementId());

		} else {
			dbEntityFieldControl = new DbEntityFieldControl();
		}

		mv.addObject("dbEntityFieldControl", dbEntityFieldControl);

		return mv;
	}

	@Override
	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(SlmServiceTarget model, HttpServletRequest req) {

		String targetHours = req.getParameter("targetHours");
		String targetMinutes = req.getParameter("targetMinutes");

		String isAutoUpgrade = req.getParameter("isAutoUpgrade");
		String autoUpgradeNodeId = req.getParameter("autoUpgradeNodeId");

		model.setTarget(targetHours + ":" + targetMinutes);

		int targetHoursInt = Integer.parseInt(targetHours);

		int targetMinutesInt = Integer.parseInt(targetMinutes);

		int targetSec = targetHoursInt * 3600 + targetMinutesInt * 60;

		model.setDistance(targetHoursInt * 3600 + targetMinutesInt * 60);
		model.setTargetSec(targetSec);
		model.setIsAutoUpgrade(isAutoUpgrade);
		model.setAutoUpgradeNodeId(autoUpgradeNodeId);
		this.getService().saveOrUpdate(model);

		return ResultMessage.newInstance(true, null, model.getId());
	}

	@RequestMapping("getSlmTarget")
	@ResponseBody
	List<SlmServiceTarget> getSlmTarget(String agreementId) {
		return this.slmServiceTargetService.findSlmServiceTargets(agreementId);
	}

	@RequestMapping("findSlmServiceTargetsValue")
	@ResponseBody
	public List<Map<String, Object>> findSlmServiceTargetsValue(
			String agreementId, String objectId) {

		return this.getService().findSlmServiceTargetsValue(agreementId,
				objectId);

	}
}
